package com.briup.pts.config.exception;

import com.briup.pts.config.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result<Void> serviceExceptionHandler(ServiceException e){
        log.error("出现业务异常",e);
        return Result.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result<Void> bindExceptionHandler(BindException e) {
        // 处理参数校验失败的原因
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringJoiner sj = new StringJoiner(" ,","参数异常:[","]");
        for (FieldError fieldError : fieldErrors) {
            sj.add(fieldError.getDefaultMessage());
        }
        // 返回失败的响应
        return Result.fail(sj.toString());
    }

    /**
     * 设置一个通用的异常处理，以便解决非业务异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> exceptionHandler(Exception e){
        log.error("出现程序内部异常",e);
        return Result.fail(e.getMessage());
    }
}
